package com.example.capturetheflag.connection;

import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import com.example.capturetheflag.joinGame.GameActivity;
import com.example.capturetheflag.helper.*;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

public class HttpGetAreaRequest extends AsyncTask<String, Void, String> 
{
	private DefaultHttpClient defaultHttpClient;
	private HttpGet httpGetrequest;
	private HttpResponse httpResponse;
	private HttpEntity httpEntity;
	private Context context;
	private Activity act;
	
	
		public HttpGetAreaRequest(Context context,Activity act)
		{
			this.context = context.getApplicationContext();
			this.act = act;
			defaultHttpClient = new DefaultHttpClient();
		}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
        Intent intent = new Intent(context, GameActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        context.startActivity(intent);
        act.finish();
	}	
		
	@Override
	protected String doInBackground(String... params) 
	{	
		httpGetrequest = new HttpGet(params[0]);
		httpGetrequest.setHeader("Accept", "application/json");
		httpGetrequest.setHeader("Content-type", "application/json");
		
		try
		{
		
		httpResponse = defaultHttpClient.execute(httpGetrequest);
		httpEntity = httpResponse.getEntity();
		
		 // Read response data into buffer
	      char[] buffer = new char[(int)httpEntity.getContentLength()];
	      InputStream stream = httpEntity.getContent();
	      InputStreamReader reader = new InputStreamReader(stream);
	      reader.read(buffer);
	      stream.close();

		  JSONObject jsonObject = new JSONObject(new String(buffer));
	
		      try{
		    	  Singleton.getInstance().gameID = jsonObject.getJSONObject("GetGameAreaResult").get("id_game").toString();
		      }
		      catch(Exception e){}
		      try
		      {
		          Singleton.getInstance().gameField = jsonObject;
		      }
		      catch(Exception e)
		      {
		    	  
		      }
		      try
		      {
		    	  Singleton.getInstance().playersPossition = jsonObject.getJSONArray("getPlayerPointsResult");
		      }
		      catch(Exception e){}
		}
		catch (Exception e) 
		{
			// TODO: handle exception
		}
		return null;
	}
}
